#pragma once
#include "TcpServer.hpp"
#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>

using std::cout;
using std::endl;
using std::string;

class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : sockfd_(sockfd), clientip_(clientip), clientport_(clientport)
    {
    }

    void run()
    {
        // echo server
        char buffer[4096];
        // 先使用sockfd描述符读取文件内容，就可以根据用户请求做出相应动作了
        // TCP面向字节流
        ssize_t n = read(sockfd_, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "client say@ " << buffer << endl;
            string echo_string = "TCP_Server echo# ";
            echo_string += buffer;

            write(sockfd_, echo_string.c_str(), strlen(echo_string.c_str())); // 写回数据流
        }
        else if (n == 0)
        {
            log(Info, "Client quit, server close fd: %d", sockfd_);
        }
        else
        {
            log(Warning, "read error, error: %d, errstring: %s", errno, strerror(errno));
        }
        close(sockfd_);
    }
    void operator()()
    {
        run();
    }

    ~Task()
    {
    }

private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;
};